
package cn.ting.mybatis.proxy;

import cn.ting.mybatis.po.Mapper;

import cn.ting.mybatis.session.SqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;


import java.util.Collection;
import java.util.List;



/**
 * 〈功能简述〉<br> 
 * 〈InvocationHandler接口的实现类〉
 * @author ting
 */
public class MapperProxyFactory implements InvocationHandler {

    private SqlSession sqlSession;

    public  MapperProxyFactory(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if(Object.class.equals(method.getDeclaringClass())){
                return method.invoke(this,args);
            }

        //key是"UserMapper接口的全限定名"+"."+方法名
        String methodName = method.getName();//方法名
        Class<?> clazz = method.getDeclaringClass();
        String clazzName = clazz.getName();//获取接口的全限定名
        String key = clazzName + "." + methodName;

        Mapper m=sqlSession.getConfiguration().getMappers().get(key);

        switch (m.getSqlType()){
            case SELECT:
            {
                Class<?> returnType = method.getReturnType();
                if (Collection.class.isAssignableFrom(returnType)) {
                    //代理对象调用任何方法，首先都会在这执行
                    //真正执行Sql语句
                    //执行Sql语句的工作:sqlSession对象的selectList(),也就是说在这要调用那个方法

                    List<Object> list = sqlSession.selectList(key);

                    return list;
                }else {
                    return sqlSession.selectOne(key,args==null?null:args[0]);
                }
               // break;
            }
            case DELETE:{
                 return sqlSession.deleteOne(key,args==null?null:args[0]);
            }
            case UPDATE:{
                return sqlSession.updateOne(key,(String)args[0]);
            }
            case INSERT:{
                return sqlSession.updateOne(key,(String)args[0]);
            }
        }
        return null;
    }
}
